#include "player.h"
#include <cmath>
#include <sstream>

Player::Player(std::string playerName, unsigned char model)
{
	std::stringstream buff;
	buff << (int)model;
	spPoc = 0;
	name = playerName;
	imgPlayer.LoadFromFile("data/" + buff.str() + ".png");
	imgPlayer.SetSmooth(false);
	imgParachute.LoadFromFile("data/p1.png");
	imgParachute.SetSmooth(false);
	imgHole.LoadFromFile("data/hole.png");
	imgHole.SetSmooth(false);
	imgHealt.LoadFromFile("data/healtbar.png");
	imgHealt.SetSmooth(false);	
	imgHealtBar.LoadFromFile("data/healtgauge.png");
	imgHealtBar.SetSmooth(false);
	spPlayer.SetImage(imgPlayer);
	spParachute.SetImage(imgParachute);
	spHole.SetImage(imgHole);
	spHealt.SetImage(imgHealt);
	spHealtBar.SetImage(imgHealtBar);
	spPlayer.SetX(320 + (model - 1) * 80);
	spHealt.SetPosition(10, 10);
	spHealtBar.SetPosition(68, 32);
	spHealtBar.SetCenter(0, 0);
	spParachute.SetX(320 + (model - 1) * 80 - 6);
	spParachute.SetCenter(0, 0);
	spHole.SetX(spPlayer.GetPosition().x - 14);
	healt = 100;
	height = 2000;
	state = PS_START;
	speed = 8;
	slow = 0.27;
	paraOpen = 0;
}

void Player::nextState()
{
	state++;
	if (state == PS_GROUND)
	{
		if (speed > 1) healt -= round(speed * 10);
		if (healt <= 0)
		{
			state = PS_DEAD;
			healt = 0;
		}
	}
}

sf::Sprite* Player::getSprite(int worldHeight)
{
	spPoc++;
	// draw parachute
	if ((spPoc == 1) && (state == PS_SLOW || state == PS_GROUND)) 
	{
		spParachute.SetY(worldHeight - height - (20 + paraOpen));
		spParachute.SetScaleY((20 + paraOpen) / 60.0f);
		return &spParachute;
	}
	if (spPoc == 1) spPoc++;
	// draw player
	if (spPoc == 2 && state != PS_DEAD) 
	{
		spPlayer.SetY(worldHeight - height - 20);
		return &spPlayer;		
	}
	if (spPoc == 2) spPoc++;
	// draw healt
	if (spPoc == 3) return &spHealt;
	if (spPoc == 4 && state != PS_DEAD) 
	{
		spHealtBar.SetScaleX((double)healt / 100.0f);
		return &spHealtBar;
	}
	if (spPoc == 4) spPoc++;
	// draw hole
	if (spPoc == 5 && state == PS_DEAD) 
	{
		spHole.SetY(worldHeight - height + 22);
		return &spHole;
	}
	if (spPoc == 5) spPoc++;
	if (spPoc == 6)
	{
		spPoc = 0;
		return NULL;
	}
}

void Player::update()
{
	if (state == PS_FREE_FALL)
	{
		height -= round(speed);
		if (height <= 0)
		{
			height = 0;
			nextState();
			return;
		}
		speed += 0.036f;
	}
	if (state == PS_SLOW)
	{
		if (paraOpen < 40) paraOpen += 5;
		height -= round(speed);
		if (height <= 0)
		{
			height = 0;
			nextState();
			return;
		}
		speed -= slow;
		slow += 0.04f;
		if (speed < 1) speed = 1;
	}
	if (state == PS_GROUND)
	{
		if (paraOpen > 0) paraOpen--;
		if (paraOpen == 0) state = PS_OVER;
	}
}

int Player::getHeight()
{
	return height;
}

unsigned char Player::getState()
{
	return state;
}

void Player::setPoints(unsigned char value)
{
	points = value;
}

void Player::setPlace(unsigned char value)
{
	place = value;
}

unsigned char Player::getPoints()
{
	return points;
}

unsigned char Player::getPlace()
{
	return place;
}

